package server

import (
	"context"
	"encoding/json"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/protobuf"
)

/**
 * @author Jared
 * @description 获取首页弹窗/签到详情处的签到信息
 * @createTime 17:46 2022/10/13
 **/
func (s *Server) GetCheckinInfo(ctx context.Context, req *protobuf.UidReq) (*protobuf.CheckinInfoResp, error) {
	if req.GetUid() <= 0 {
		details, err := GetMarkedDetails(0)
		if err != nil {
			return nil, err
		}
		return &protobuf.CheckinInfoResp{
			Continuous:     0,
			IsCheckedToday: false,
			CheckinDetails: details,
		}, nil
	}
	checkin, err := db_main.GetUserCheckInByUid(int(req.Uid))
	if err != nil {
		return nil, err
	}

	err = GenUserCheckin(int(req.Uid), checkin)
	if err != nil {
		return nil, err
	}

	continuous, _, isCheckedToday, err := CalContinuous(checkin)
	if err != nil {
		return nil, err
	}

	details, err := GetMarkedDetails(continuous)
	if err != nil {
		return nil, err
	}

	return &protobuf.CheckinInfoResp{
		Continuous:     uint32(continuous),
		IsCheckedToday: isCheckedToday,
		CheckinDetails: details,
	}, nil
}

/**
 * @author Jared
 * @description 点击签到
 * @createTime 17:46 2022/10/13
 **/
func (s *Server) CheckinToday(ctx context.Context, req *protobuf.UidReq) (*protobuf.CheckinResp, error) {
	checkin, err := db_main.GetUserCheckInByUid(int(req.Uid))
	if err != nil {
		return nil, err
	}

	err = GenUserCheckin(int(req.Uid), checkin)
	if err != nil {
		return nil, err
	}

	continuous, continuousTotal, isCheckedToday, err := CalContinuous(checkin)
	if err != nil {
		return nil, err
	}

	if !isCheckedToday {
		return DoCheckin(int(req.Uid), continuous, continuousTotal, checkin)
	}

	return &protobuf.CheckinResp{
		IsSucceed:  false,
		Continuous: uint32(continuous),
		RewardList: []*protobuf.GetTaskRewardList{},
	}, nil
}

/**
 * @author Jared
 * @description 签到详情-签到历史
 * @createTime 17:46 2022/10/13
 **/
func (s *Server) GetCheckinHistory(ctx context.Context, req *protobuf.UidReq) (*protobuf.CheckinHistoryResp, error) {
	resp := &protobuf.CheckinHistoryResp{CheckinHistory: []*protobuf.CheckinHistory{}}

	history, err := db_main.GetUserCheckinHistory(map[string]interface{}{"uid": req.Uid}, 1, 30)
	for _, v := range history {
		var pbRewards []*protobuf.GetTaskRewardList
		err = json.Unmarshal([]byte(v.RewardDesc), &pbRewards)
		if err != nil {
			continue
		}
		resp.CheckinHistory = append(resp.CheckinHistory, &protobuf.CheckinHistory{
			CheckinTime: v.CheckinTime.Format(timehelper.TIME_LAYOUT_FORMAT_7),
			RewardDesc:  pbRewards,
		})
	}

	return resp, err
}
